package com.cse.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cse.constants.SystemConstants;
import com.cse.dto.Result;
import com.cse.entity.Shop;
import com.cse.mapper.ShopMapper;
import com.cse.service.IShopService;
import com.cse.utils.CacheClient;
import lombok.RequiredArgsConstructor;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static com.cse.constants.RedisConstants.*;
import static com.cse.constants.SystemConstants.SHOP_ERROR;
import static com.cse.constants.SystemConstants.SHOP_ID_ERROR;

@Service
@RequiredArgsConstructor
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    private final StringRedisTemplate stringRedisTemplate;
    private final CacheClient cacheClient;


    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //判断是否需要根据坐标查询
        if (x==null || y==null) {
            //不需要，直接根据类型分页查询
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
         return Result.ok(page.getRecords());
        }
        //计算分页数据
        int from=(current-1)*SystemConstants.DEFAULT_PAGE_SIZE;
        int end=current*SystemConstants.DEFAULT_PAGE_SIZE;
        String key=SHOP_GEO_KEY+typeId;
        //查询redis，按照距离分页排序 结果：shopId distance
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(
                key,
                GeoReference.fromCoordinate(x, y),
                new Distance(900000000),
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
        );
        if (results==null){
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size()<=from) {
            //没有下一页 返回空
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids=new ArrayList<>(list.size());
        Map<String,Distance> distanceMap=new HashMap<>(list.size());
        //解析出id
        list.stream().skip(from).forEach(result->{
            //获取店铺id
                    String shopIdStr = result.getContent().getName();
                    ids.add(Long.valueOf(shopIdStr));
                    //获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr,distance);
                });
                      //根据id查询Shop
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        //返回
        return Result.ok(shops);
    }

    @Override
    public Result queryById(Long id) {
        Shop shop=cacheClient
                .queryWithPassThrough(CACHE_SHOP_KEY,id,
                        Shop.class,this::getById,
                        CACHE_SHOP_TTL, TimeUnit.MINUTES);
        if (shop==null) {
            return Result.fail(SHOP_ERROR);
        }
        return Result.ok(shop);
    }


    @Transactional
    public Result updata(Shop shop) {
        Long id = shop.getId();
        if (id==null) {
            return Result.fail(SHOP_ID_ERROR);
        }
        updateById(shop);
        stringRedisTemplate.delete(CACHE_SHOP_KEY +id);

        return Result.ok();
    }
}
